<template>
  <basic-container>
    <section class="haruyuki-bg-color-white">
      <div class="haruyuki-flex-space-between haruyuki-align-items-center">
        <div class="haruyuki-title haruyuki-size-16">
          <i class="el-icon-tickets"></i><span class="haruyuki-ml-6">订单信息</span>
        </div>
        <el-button type="primary" size="mini" @click="clickCopy">一键复制</el-button>
      </div>
      <div class="haruyuki-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <span class="wordBreak">服务商编号：{{orderInfo.serviceNo}}</span>
          </el-col>
          <el-col :span="8">
            <span class="wordBreak">服务商名称：{{orderInfo.serviceName}}</span>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-row :gutter="20">
              <el-col :span="24">
                <span class="wordBreak">订单号：{{orderInfo.orderCode}}</span>
              </el-col>
              <el-col :span="24">
                <span class="wordBreak">子订单号：{{orderQuery.subOrderCode}}</span>
              </el-col>
              <el-col :span="24">
                <span class="wordBreak">订单日期：{{orderInfo.createTime}}</span>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="20">
              <el-col :span="24">
                <span class="wordBreak">收货人姓名：{{orderInfo.consignee}}</span>
              </el-col>
              <el-col :span="24">
                <span class="wordBreak">联系方式：{{orderInfo.consigneePhone}}</span>
              </el-col>
              <el-col :span="24" v-show="orderInfo.expressType">
                <span class="wordBreak">收货地址</span>：{{orderInfo.consigneeAddress}}</span>
              </el-col>
              <el-col :span="24" v-show="orderInfo.expressType">
                <span class="wordBreak">所属省市区</span>：{{ orderInfo.provinceName }}/{{ orderInfo.cityName }}/{{ orderInfo.areaName }}</span>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row :gutter="20">
              <el-col :span="24">
                <span class="wordBreak">物流名称：{{orderInfo.expressTypeName}}</span>
              </el-col>
              <el-col :span="24">
                <span class="wordBreak">邮费：{{orderInfo.expressFee}}</span>
              </el-col>
              <el-col :span="24">
                <span class="wordBreak">物流单号：{{orderInfo.expressCode}}</span>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <!-- <div class="haruyuki-title haruyuki-size-16 dg-wrap dg-line">
         <i class="el-icon-edit"></i><span class="haruyuki-ml-6">备注信息</span>
      </div>
      <div class="haruyuki-content">
        <div>{{orderInfo.remark||'无'}}</div>
      </div> -->

      <div class="haruyuki-flex-space-between haruyuki-align-items-center">
        <div class="haruyuki-title haruyuki-size-16">
          <i class="el-icon-tickets"></i><span class="haruyuki-ml-6">商品信息</span>
        </div>
      </div>
      <div class="haruyuki-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <span class="wordBreak">行业分类：{{orderZInfo.classIndustryName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="wordBreak">行业大类：{{orderZInfo.classSuperName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="wordBreak">行业小类：{{orderZInfo.classSubName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="wordBreak">品牌：{{orderZInfo.classBrandName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="wordBreak">商品名称：{{orderZInfo.productName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="wordBreak">型号名称：{{orderZInfo.specificationName}}</span>
          </el-col>
          <el-col :span="6">
            <span class="wordBreak">订单数量：{{orderZInfo.num}}</span>
          </el-col>
        </el-row>
      </div>

      <div class="haruyuki-flex-space-between haruyuki-align-items-center">
        <div class="haruyuki-title haruyuki-size-16">
          <i class="el-icon-setting"></i><span class="haruyuki-ml-6">设备信息</span>
        </div>
      </div>
      <div class="haruyuki-content">
        <el-form :model="setForm" ref="setForm" size="small" label-width="120px" class="demo-ruleForm">
          <el-row :gutter="20">
            <el-col :span="6">
              <span class="wordBreak">物流方式：{{orderInfo.expressTypeName}}</span>
            </el-col>
            <el-col :span="6">
              <span class="wordBreak">邮费</span>：{{orderInfo.expressFee}}</span>
            </el-col>
            <el-col :span="6" v-if="orderInfo.expressType">
              <el-form-item label="物流名称" prop="expressName"
              :rules="[
                { required: true,message: '物流名称不能为空', trigger: ['blur','change']},
              ]"
              >
                <el-input v-model="setForm.expressName" placeholder="请输入物流名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="orderInfo.expressType">
              <el-form-item label="物流单号" prop="expressCode" 
              :rules="[
                { required: true,message: '物流单号不能为空', trigger: ['blur','change']},
              ]"
              >
                <el-input v-model="setForm.expressCode" placeholder="请输入物流单号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="SN编号" prop="sn"
              :rules="[
                { required: true,message: 'SN编号不能为空', trigger: ['blur','change']},
              ]"
              >
                <el-input v-model="setForm.sn" placeholder="请输入SN编号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物联网卡返现" prop="iotAmt" 
              :rules="[
                { required: true,message: '物联网卡返现不能为空', trigger: ['blur','change']},
              ]"
              >
                <el-input v-model="setForm.iotAmt" placeholder="请输入物联网卡返现" onkeyup="value=value.replace(/[^\d^\.]+/g,'');value=value.toString().match(/^\d+(?:\.\d{0,2})?/)">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-col>
            <div class="zfb">
              <el-button type="primary" size="small" @click="addSn()">添加</el-button>
              <el-button type="primary" size="small" @click="excelBox = true">批量导入</el-button>
            </div>
          </el-row>
        </el-form>
      </div>

      <avue-crud
        :option="option"
        :data="snList"
        ref="crud"
      >
        <template slot-scope="scope" slot="menu">
          <el-button size="small" type="text" @click.stop="handleDel(scope.row)">删除</el-button>
        </template>
        <template slot-scope="{row}" slot="remark2">
          <div class="picture-preview" @click="dialogRefundVisible = true">{{row.remark2}}</div>
        </template>
      </avue-crud>
      <div class="dialog-footer" style="margin-top:20px">
        <el-button type="primary" size="small" :disabled="fhDisabled" @click="fhSubmit()">确认发货</el-button>
      </div>
    </section>

    <!-- 导入 -->
    <el-dialog
        title="数据导入"
        append-to-body
        :visible.sync="excelBox"
        v-if="excelBox"
        width="555px"
      >
        <avue-form
          :option="excelOption"
          v-model="excelForm"
          :before-close="handleCloseExcel"
          ref="excelForm"
        >
          <template slot="excelFile">
            <el-upload
              ref="upload"
              class="upload-demo"
              drag
              :limit="1"
              :http-request="httpRequest"
              :on-success="onSuccess"
              :on-change="handleChange"
              :on-remove="handleRemove"
              multiple
              :file-list="fileList"
              :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">请上传 .xls,.xlsx 标准格式文件</div>
            </el-upload>
            <div style="display: flex; justify-content: flex-end;">
              <el-button type="primary" @click="uploadSubmit" :disabled="uploadDisabled" v-show="fileList.length">
                确定上传<i class="el-icon-upload2 el-icon--right"></i>
              </el-button>
            </div>
          </template>
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>
  </basic-container>
</template>
<script>
import { apiDetail, apizDetail, apiFaHuo, uploadFile, getExportTemplate,apicheckSN } from '@/api/rb-oem/shop/orderList'
import {downloadFileExcel} from "@/util/util";
let id = 1;
export default {
  data() {
    return {
      // str----发货
      fhShow:false,
      fhDisabled:false,
      fhForm:{
        wuLiuTypes:'',
        wuLiuName:'',
      },
      // end----发货
      orderInfo: {}, //订单详情
      orderZInfo:{}, //子订单详情
      dialogRefundVisible: false, //退款 dialog
      snList: [], //SN 集合
      option: {
        // height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        searchMenuSpan: 24,
        columnBtn: false,
        // menu:false,
        // menuWidth:140,
        refreshBtn:false,
        searchBtn:false,
        selectClearBtn:false,
        indexLabel:'序号',
        selection:false,
        column: [
           {
            label: "商品名称",
            prop: "productName",
            type: "input",
            overHidden:true
          },
          
          {
            label: "商品型号",
            prop: "specificationName",
            type: "input",
            overHidden:true
          },
          {
            label: "子订单编号",
            prop: "subOrderCode",
            type: "input",
          },
          {
            label: "商品SN编号",
            prop: "sn",
            type: "input",
            overHidden:true,
          },
           {
            label: "单价",
            prop: "price",
            type: "input",
            overHidden:true,
          },
          {
            label: "物联网返现",
            prop: "iotAmt",
            type: "input",
            overHidden:true,
          }
        ]
      },
      setForm:{
        expressName:"",
        expressCode:"",
        sn:"",
        iotAmt:"",
      },
      orderQuery:{},//路径参数
      // str----批量导入
      excelBox:false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "物流名称",
            prop: "expressName",
            span: 24,
            clearable: true,
            rules: [{
              required: true,
              message: "请输入物流名称",
              trigger: "blur"
            }],
            display:false,
          },
          {
            label: "物流单号",
            prop: "expressCode",
            span: 24,
            clearable: true,
            rules: [{
              required: true,
              message: "请输入物流单号",
              trigger: "blur"
            }],
            display:false,
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              url:'link',
              name:'originalName',
              res: "data",
            },
            headers: {
              "Content-Type": "multipart/form-data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/mall/mallApi/deliverGoodsExcel",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ]
      },
      uploadDisabled:false,
      fileList:[]
      // end----批量导入
    };
  },
  computed: {
    // 备注
    getRemark(){
      return (val) => {
        if (val) {
          return val;
        } else {
          return "无";
        }
      };
    }
  },
  created() {
    this.infoData();
  },
  methods: {
    // 复制
    clickCopy() {
      // ht 字符串 | ht格式别乱动
let ht = `
收件人：${this.orderInfo.consignee}
联系方式：${this.orderInfo.consigneePhone}
所属省市区：${ this.orderInfo.provinceName }/${ this.orderInfo.cityName }/${ this.orderInfo.areaName }
收货地址：${this.orderInfo.consigneeAddress}
`;
      const save = function (e) {
        e.clipboardData.setData("text/plain", ht);
        e.preventDefault(); // 阻止默认行为
      };
      const once = {
        once: true,
      };
      document.addEventListener("copy", save, once); // 添加一个copy事件
      document.execCommand("copy"); // 执行copy方法
      this.$message({ message: "复制成功", type: "success" });
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    uploadSubmit(){
      this.$refs.upload.submit();
    },
    /* 关闭弹框 */
    handleCloseExcel(done){
      this.excelForm = {};
      this.fileList =[];
      done();
    },
    /* 批量文件上传 */
    httpRequest(option){
      this.$refs.excelForm.validate((valid, done, msg) => {
        if (valid) {
          this.uploadDisabled = true ;
            let parm = {
              expressCode:this.excelForm.expressCode,
              expressName:this.excelForm.expressName,
              subOrderCode:this.orderZInfo.subOrderCode,
            }
            uploadFile(option.file, option.file.name, parm).then((res) => {
              this.uploadDisabled = false ;
              this.$message({ type: "success", message: res.data.msg });

              this.$router.$avueRouter.closeTag();
              this.$router.replace({ path: "/rb-oem/shop/orderListDetail",query:{orderCode:this.orderInfo.orderCode}});
              this.fhDisabled = false;
              done()
            },() =>{
              this.uploadDisabled = false ;
            })
        } else {
          return false;
        }
      })
      
    },
    handleTemplate(){
      getExportTemplate().then((res) => {
        downloadFileExcel(res);
      });
    },
    handleDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          this.snList.splice(row.$index,1)

          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    /* 添加入库 */
    addSn(){
      let that = this;
      let arr = [];
      this.$refs.setForm.validateField(['sn','iotAmt'],(valid) => {
        if (!valid) {
          arr.push(valid);
          if(arr.length==2&&arr.every((item) => item === "")){
            let snParam = {
              sn:that.setForm.sn,
              iotAmt:that.setForm.iotAmt,
            }
            apicheckSN(snParam).then(res =>{
              let param = {
                productName:that.orderZInfo.productName,
                specificationName:that.orderZInfo.specificationName,
                price:that.orderZInfo.price,
                subOrderCode:that.orderZInfo.subOrderCode,
                sn:that.setForm.sn,
                iotAmt:that.setForm.iotAmt,
              }

              let storeData = [param];
              if (this.snList.length > 0) {
                // 首先构造Object
                // reduce  初始值（或者上一次回调函数的返回值），当前元素值，当前索引，调用 reduce 的数组。
                const idSet = this.snList.reduce((acc, v) => {
                    acc[v.sn] = true;
                    return acc;
                }, {});
                let result = [];

                result = storeData.filter(v => !idSet[v.sn]);
                
                if (result.length > 0) {
                  for (let i = 0; i < result.length; i++) {
                    this.snList.unshift({id: id++, ...result[i]});
                  }
                } else {
                  this.$message({
                    type: "warning",
                    message: "所输入的SN编号不能相同!",
                  });
                }
              } else {
                for (let i = 0; i < storeData.length; i++) {
                  this.snList.unshift({id: id++, ...storeData[i]});
                }
              }
            });
          }else{
            return;
          }
        }
      });
    },
    /* 确认发货 */
    fhSubmit(){
      let that = this;

      this.$refs.setForm.validate((valid) => {
        if (valid) {
          this.fhDisabled = true;

          let parm = {
            expressCode:this.setForm.expressCode,
            expressName:this.setForm.expressName,
            subOrderCode:this.orderZInfo.subOrderCode,
            snList:this.snList
          }
          
          apiFaHuo(parm).then((res) => {
            this.$router.$avueRouter.closeTag();
            this.$router.replace({ path: "/rb-oem/shop/orderListDetail",query:{orderCode:this.orderInfo.orderCode}});
            
            this.fhDisabled = false;
          }, (error) => {
            this.fhDisabled = false;
          });
        } else {
          return false;
        }
      });
    },
    /* 页面加载 初始化请求详情接口 */
    infoData() {
      console.log('页面加载')

      let that = this;
      this.orderQuery = {
        orderCode:this.$route.query.orderCode,
        subOrderCode:this.$route.query.subOrderCode
      };

      apiDetail({ orderCode: this.orderQuery.orderCode }).then((res) => {
        this.orderInfo = res.data.data;
        if(this.orderInfo.expressType){
          const expressCode = that.findObject(that.excelOption.column, "expressCode");
          expressCode.display = true;

          const expressName = that.findObject(that.excelOption.column, "expressName");
          expressName.display = true;
        }
      })

      apizDetail({ subOrderCode: this.orderQuery.subOrderCode }).then((res) => {
        this.orderZInfo = res.data.data;
      })
    },
    /* 返回页面 */
    goBack() {
      this.$router.$avueRouter.closeTag();
      this.$router.replace({ path: "/rb-oem/shop/orderListDetail" });
    }
  },
};
</script>

<style lang="scss" scoped>
.picture-preview {
  color: #409eff;
  cursor: pointer;
}

.merchant-title {
  font-weight: bold;
}

/deep/ .avue-crud__menu{
  display: none !important;
}
.wordBreak{
  word-break: break-word;
}
/deep/ .el-tag--dark.el-tag--success {
  border: none !important;
}
.centers{
  text-align: center;
}
::v-deep .el-form--inline .el-form-item__content{
  width: calc(100% - 120px);
}
::v-deep .el-form--inline .el-form-item {
  width: 100%;
}
.dialog-footer{
  display: flex;
  justify-content: center;
}
.zfb{
  display: flex;
  justify-content: space-between;
  align-content: center;
}
</style>